package com.blast.manager.delay.presenter

import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blast.manager.delay.DelayActivity
import com.blast.manager.delay.adapter.DelayAdapter
import com.blast.manager.delay.ui.DelayRepeatActivity
import com.wxl.common.base.AbsActivity
import com.wxl.common.event.RefreshDataEvent
import com.wxl.common.life.LifecycleManager
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.LayoutHelper
import com.wxl.common.util.ObservableUtil
import com.wxl.common.wiget.LeiGuanTipPop
import io.reactivex.functions.Action
import kotlinx.android.synthetic.main.activity_delay_layout.view.*

class ShowDelayDataPresenter : AbsDelayPresenter() {


    private var mDelayAdapter: DelayAdapter? = null

    private val mRepeatData = ArrayList<LeiGuanEntity>()//重复的数据

    private val mCacheDataUids = ArrayList<String>()//数据Uid

    private val mData = ArrayList<LeiGuanEntity>() // 雷管数据

    private var importNum = 0

    private var canScrollVertically = true

    override fun onDelayCreated(vararg args: Any) {
        rootView.delayListView.layoutManager = object :LinearLayoutManager(context){
            override fun canScrollVertically(): Boolean {
                return canScrollVertically
            }
        }

        readLeiGuanDataDbRefresh()

        val mRefreshDataEvent = RefreshDataEvent()
        mRefreshDataEvent.observe((context as AbsActivity), Observer {
            if (it.isRefresh) {
                readLeiGuanDataDbRefresh()
            }
        })
        LifecycleManager.manager.registerLiveData(
            mRefreshDataEvent,
            (context as AbsActivity).lifecycle
        )
    }


    private fun readLeiGuanDataDbRefresh() {
        mCacheDataUids.clear()
        DBHelper.queryLeiGuanEntity(object :
            ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                importNum = 0
                t.forEach {
                    mCacheDataUids.add(it.UID)
                }
                mData.clear()
                mData.addAll(t)
                if (mData.isNotEmpty()) {
                    mData[0].isSelect = true
                    notifyDelayDataChanged(t)
                    mDelayAdapter?.position = 0
                } else {
                    rootView.delayListView.visibility = View.GONE
                    rootView.delayEmptyView.visibility = View.VISIBLE
                }
            }
        })
    }

    private fun notifyDelayDataChanged(data: List<LeiGuanEntity>) {
        if (mDelayAdapter == null) {
            LayoutHelper.getDetonatorTitleViewsWidth(rootView.delayTitleLayout,object : ObservableUtil.Companion.OnNextCallback<ArrayList<Int>>(){
                override fun onNext(t: ArrayList<Int>) {
                    mDelayAdapter = DelayAdapter(data)
                    mDelayAdapter?.setWidths(t)
                    mDelayAdapter?.bindToRecyclerView(rootView.delayListView)
                    mDelayAdapter?.setOnEditorCallback(object : DelayAdapter.OnEditorCallback {
                        override fun onEditorResult() {
                            notifyCanScrollVerticallyChanged(true)
                        }
                    })
                }
            })
        } else {
            mDelayAdapter?.setNewData(data)
        }
        if (data.isEmpty()) {
            rootView.delayListView.visibility = View.GONE
            rootView.delayEmptyView.visibility = View.VISIBLE
        } else {
            rootView.delayListView.visibility = View.VISIBLE
            rootView.delayEmptyView.visibility = View.GONE
        }
    }

    fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        mDelayAdapter?.onKeyDown(keyCode, event)
        if(mDelayAdapter != null){
            return mDelayAdapter!!.isEditor()
        }
        return false
    }

    fun getTotal():Int{
        return mData.size
    }

    /**
     * 检查重复并添加雷管数据
     */
    fun checkLeiGuanRepeat(lg: LeiGuanEntity) {
        if (mCacheDataUids.contains(lg.UID)) {
            mRepeatData.add(lg)
        } else {
            importNum++
            mCacheDataUids.add(lg.UID)
            mData.add(lg)
        }
    }


    /**
     * 开始导入时恢复初始状态
     */
    fun resetStartImport() {
        mRepeatData.clear()
        importNum = 0
    }


    /**
     * 刷新数据
     */
    fun refreshData() {
        notifyDelayDataChanged(mData)
    }


    /**
     * 保存数据到db
     */
    fun saveDataToDb(callback: ObservableUtil.Companion.OnNextCallback<Boolean>) {
        DBHelper.insertNewLeiGuanData(callback, *mData.toTypedArray())
    }

    /**
     * 延时2s显示统计结果，be:进度条延时2s关闭
     */
    fun delayShowImportDataPop(totalNum: Int) {
        saveDataToDb(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                ObservableUtil.delay(2000, Runnable {
                    LeiGuanTipPop.show(
                        context,
                        mCacheDataUids.size.toString(),
                        mRepeatData.size.toString(),
                        totalNum.toString(),
                        object : Action {
                            override fun run() {
                                if (mRepeatData.isNotEmpty()) {
                                    (context as DelayActivity).addLog("查看重复数据","重复${mRepeatData.size}条")
                                    DelayRepeatActivity.start(context,mData,mRepeatData)
                                }
                            }
                        })
                })
            }
        })
    }


    fun getData(): ArrayList<LeiGuanEntity> {
        return mData
    }


    fun clearData() {
        DBHelper.deleteLeiGuan(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                mCacheDataUids.clear()
                mData.clear()
                mRepeatData.clear()
                refreshData()
            }
        }, *mData.toTypedArray())
    }

    fun getSelectPosition(): Int {
        if (mDelayAdapter != null) {
            return mDelayAdapter!!.position
        }
        return -1
    }


    /**
     * 通知删除
     */
    fun notifyItemRemoved(position: Int) {
        mDelayAdapter?.data?.removeAt(position)
        mData.removeAt(position)
        mDelayAdapter?.notifyDataSetChanged()
        if (mDelayAdapter!!.position == mData.size) {
            mDelayAdapter!!.position = mData.size - 1
        }
        if (mData.isEmpty()) {
            rootView.delayListView.visibility = View.GONE
            rootView.delayEmptyView.visibility = View.VISIBLE
        }
    }

    /**
     * 刷新
     */
    fun notifyItemDataChanged(position: Int) {
        mDelayAdapter?.notifyItemChanged(position)
        notifyCanScrollVerticallyChanged(position != 0)
        rootView.delayListView.scrollToPosition(position)
    }

    fun notifyCanScrollVerticallyChanged(canScrollVertically:Boolean){
        this.canScrollVertically  = canScrollVertically
    }

    fun isEditor(): Boolean {
        if (mDelayAdapter != null) {
            return mDelayAdapter!!.isEditor()
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        mCacheDataUids.clear()
        mData.clear()
        mRepeatData.clear()
        mDelayAdapter?.release()
        mDelayAdapter  = null
    }
}